package com.xcw.jac;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class FormRequestExample {
    public static void main(String[] args) throws IOException {
        String url = "http://example.com/submit";  // 表单提交的URL

        // 表单数据
        Map<String, String> formData = new HashMap<>();
        formData.put("username", "user123");
        formData.put("password", "pass123");

        // 构建表单数据字符串
        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, String> entry : formData.entrySet()) {
            if (postData.length() != 0) {
                postData.append('&');
            }
            postData.append(entry.getKey());
            postData.append('=');
            postData.append(entry.getValue());
        }

        // 将表单数据转换为字节数组
        byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);


        // 创建连接
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);

        // 发送请求
        try (OutputStream outputStream = conn.getOutputStream()) {
            outputStream.write(postDataBytes);
        }

        // 获取响应
        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 读取响应内容
        } else {
            // 处理错误情况
        }

        conn.disconnect();
    }
}